package com.ruoyi.task.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.task.domain.CheckResult;
import com.ruoyi.task.domain.CheckRisk;
import com.ruoyi.task.domain.RiskDetailInfo;
import com.ruoyi.task.domain.TaskDetail;
import com.ruoyi.task.domain.TaskDetailExportResult;
import com.ruoyi.task.domain.TaskDetailResult;
import com.ruoyi.task.domain.TaskDetailResultParams;
import com.ruoyi.task.domain.TaskRiskImage;
import com.ruoyi.task.mapper.TaskDetailMapper;
import com.ruoyi.task.mapper.TaskDetailResultMapper;
import com.ruoyi.task.service.IHaoYunService;
import com.ruoyi.task.service.ITaskDetailResultService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.TaskExecutor;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * 任务分析结果明细Service业务层处理
 *
 * @author huangshibao
 * @date 2025-06-18
 */
@Slf4j
@Service
public class TaskDetailResultServiceImpl implements ITaskDetailResultService {

    @Autowired
    private TaskDetailResultMapper taskDetailResultMapper;

    @Autowired
    private TaskDetailMapper taskDetailMapper;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IHaoYunService haoYunService;

    @Value("${agentServerIp:http://10.223.7.21:9000}")
    private String agentServerIp;

    @Autowired
    private TaskExecutor taskExecutor;

    /**
     * 查询任务分析结果明细
     *
     * @param priKey 任务分析结果明细主键
     * @return 任务分析结果明细
     */
    @Override
    public TaskDetailResult selectTaskDetailResultByPriKey(Long priKey) {
        return taskDetailResultMapper.selectTaskDetailResultByPriKey(priKey);
    }

    /**
     * 查询任务分析结果明细列表
     *
     * @param taskDetailResult 任务分析结果明细
     * @return 任务分析结果明细
     */
    public List<TaskDetailResult> selectTaskDetailResultList(
            TaskDetailResultParams taskDetailResult) {
        if (StringUtils.isNotBlank(taskDetailResult.getScenariosType())) {
            taskDetailResult.setScenariosTypeList(
                    StringUtils.str2List(taskDetailResult.getScenariosType(), ",", true, true));
        }

        return taskDetailResultMapper.queryTaskDetailResultList(taskDetailResult);
    }


    @Override
    public Map<String, Object> exportTaskDetailResultList(TaskDetailResultParams taskDetailExport) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<String> metaLite = getExcelNamesAsList();
            result.put("meta", metaLite);

            if (taskDetailExport.getScenariosType() != null) {
                taskDetailExport.setScenariosTypeList(
                        StringUtils.str2List(taskDetailExport.getScenariosType(), ",", true, true));
            }
            List<TaskDetailExportResult> resultList = taskDetailResultMapper.selectTaskDetailExportResult(
                    taskDetailExport);
            List<List<String>> rows = new ArrayList<>();
            List<String> columns = new ArrayList<>();
            for (TaskDetailExportResult taskDetailExportResult : resultList) {
                columns = new ArrayList<>();
                columns.add(taskDetailExportResult.getId());
                columns.add(taskDetailExportResult.getBranchCode());
                columns.add(taskDetailExportResult.getBranchName());
                columns.add(taskDetailExportResult.getDeptCode());
                columns.add(taskDetailExportResult.getDeptName());
                columns.add(taskDetailExportResult.getCameraName());
                columns.add(taskDetailExportResult.getScenariosName());
                columns.add(taskDetailExportResult.getRiskReason());
                columns.add(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,
                        taskDetailExportResult.getStartTime()));
                columns.add(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,
                        taskDetailExportResult.getEndTime()));
                columns.add(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,
                        taskDetailExportResult.getCreateTime()));
                columns.add(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,
                        taskDetailExportResult.getUpdateTime()));

                rows.add(columns);
            }
            result.put("data", rows);
        } catch (Exception e) {
            log.error("exportTaskDetailResultList error ", e);
        }
        return result;
    }

    private List<String> getExcelNamesAsList() {
        List<String> excelNames = new ArrayList<>();
        excelNames.add("主键(id)");
        excelNames.add("分行ID(branch_code)");
        excelNames.add("分行名称(branch_name)");
        excelNames.add("支行ID(dept_code)");
        excelNames.add("支行名称(dept_name)");
        excelNames.add("摄像头名称(camera_name)");
        excelNames.add("场景名称(scenarios_name)");
        excelNames.add("风险原因(risk_reason)");
        excelNames.add("开始时间(start_time)");
        excelNames.add("结束时间(end_time)");
        excelNames.add("创建时间(create_time)");
        excelNames.add("更新时间(update_time)");

        return excelNames;
    }

    @Override
    public int countTaskDetailResultList(TaskDetailResultParams taskDetailResult) {
        if (taskDetailResult.getScenariosType() != null) {
            taskDetailResult.setScenariosTypeList(
                    StringUtils.str2List(taskDetailResult.getScenariosType(), ",", true, true));
        }
        return taskDetailResultMapper.countTaskDetailResultList(taskDetailResult);
    }

    /**
     * 导出数据
     *
     * @param taskDetailExport
     * @return
     */
    @Override
    public List<TaskDetailExportResult> selectTaskDetailExportResult(
            TaskDetailResultParams taskDetailExport) {
        if (taskDetailExport.getScenariosType() != null) {
            taskDetailExport.setScenariosTypeList(
                    StringUtils.str2List(taskDetailExport.getScenariosType(), ",", true, true));
        }
        return taskDetailResultMapper.selectTaskDetailExportResult(taskDetailExport);
    }


    /**
     * 新增任务分析结果明细
     *
     * @param taskDetailResult 任务分析结果明细
     * @return 结果
     */
    @Override
    public int insertTaskDetailResult(TaskDetailResult taskDetailResult) {
        taskDetailResult.setCreateTime(DateUtils.getNowDate());
        return taskDetailResultMapper.insertTaskDetailResult(taskDetailResult);
    }

    /**
     * 修改任务分析结果明细
     *
     * @param taskDetailResult 任务分析结果明细
     * @return 结果
     */
    @Override
    public int updateTaskDetailResult(TaskDetailResult taskDetailResult) {
        taskDetailResult.setUpdateTime(DateUtils.getNowDate());
        return taskDetailResultMapper.updateTaskDetailResult(taskDetailResult);
    }

    /**
     * 批量删除任务分析结果明细
     *
     * @param priKeys 需要删除的任务分析结果明细主键
     * @return 结果
     */
    @Override
    public int deleteTaskDetailResultByPriKeys(Long[] priKeys) {
        try {
            List<String> ids = taskDetailResultMapper.selectTaskDetailResultIdList(priKeys);
            int count = haoYunService.deleteTaskDetailResult(ids);
            log.info("deleteTaskDetailResultByPriKeys hy success = {}", count);
        } catch (Exception e) {
            log.error("deleteTaskDetailResultByPriKeys error ", e);
        }

        return taskDetailResultMapper.deleteTaskDetailResultByPriKeys(priKeys);
    }

    /**
     * 删除任务分析结果明细信息
     *
     * @param priKey 任务分析结果明细主键
     * @return 结果
     */
    @Override
    public int deleteTaskDetailResultByPriKey(Long priKey) {
        return taskDetailResultMapper.deleteTaskDetailResultByPriKey(priKey);
    }

    @Override
    public boolean sceneCheckResult(List<RiskDetailInfo> riskDetailInfoList) {
        try {

            // 查询数据库任务数据，补全其他信息
            TaskDetail taskDetail = taskDetailMapper.queryTaskDetailByTaskId(
                    riskDetailInfoList.get(0).getTaskId());

            log.info("sceneCheckResult db data = {}", JSON.toJSONString(taskDetail));
            if (taskDetail != null) {

                // 查询场景名称
                String sceneName = sysDictDataService.selectDictLabel("task_scenarios_type",
                        riskDetailInfoList.get(0).getSceneId());

                TaskDetailResult taskDetailResult = null;
                for (RiskDetailInfo riskDetailInfo : riskDetailInfoList) {
                    taskDetailResult = new TaskDetailResult();
                    taskDetailResult.setId(riskDetailInfo.getUid());
                    taskDetailResult.setTaskId(riskDetailInfo.getTaskId());
                    taskDetailResult.setBranchCode(taskDetail.getSubBankCode());
                    taskDetailResult.setBranchName(taskDetail.getSubBankName());
                    taskDetailResult.setDeptCode(taskDetail.getBankCode());
                    taskDetailResult.setDeptName(taskDetail.getBankName());
                    taskDetailResult.setCameraName(taskDetail.getChannelRemark());
                    taskDetailResult.setScenariosType(riskDetailInfo.getSceneId());
                    taskDetailResult.setScenariosName(sceneName);
                    taskDetailResult.setRiskReason(riskDetailInfo.getRiskReason());
                    taskDetailResult.setStartTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS,
                            riskDetailInfo.getRiskStartTime()));
                    taskDetailResult.setEndTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS,
                            riskDetailInfo.getRiskEndTime()));
                    taskDetailResult.setTaskType(taskDetail.getTaskType());

                    // 插入数据库
                    int count = taskDetailResultMapper.saveTaskDetailResult(taskDetailResult);
                    log.info("sceneCheckResult save uid = {},  count = {}", riskDetailInfo.getUid(),
                            count);
                }

                return true;
            }
        } catch (BaseException ex) {
            throw ex;
        } catch (Exception e) {
            log.error("sceneCheckResult error ", e);
        }
        return false;
    }

    @Override
    public boolean sceneCheckImage(TaskRiskImage riskImage) {
        try {
            String fileName = String.format("%s_%06d.jpg", riskImage.getUid(), riskImage.getSortNo());

            log.info("sceneCheckImage begin fileName = {}", fileName);
            Map<String, String> map = new HashMap<>();
            map.put("base64", riskImage.getRiskImage());
            map.put("file_name", fileName);
            map.put("task_id", riskImage.getTaskId());
            map.put("risk_id", riskImage.getUid());

            // 上传图片
            String params = JSON.toJSONString(map);
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", MediaType.APPLICATION_JSON_VALUE);

            String url = agentServerIp + "/api/v1/file/image_upload";

            String rspStr = HttpUtils.sendPost(url, params, headers, 10000);
            log.info("sceneCheckImage end fileName = {}, result = {}", fileName, rspStr);
            if (StringUtils.isBlank(rspStr)) {
                return false;
            }
            JSONObject jsonObject = JSON.parseObject(rspStr);
            if (StringUtils.equals(jsonObject.getString("responseCode"), "0")) {
                jsonObject.getJSONObject("responseData").getString("image_dir");
                return true;
            } else {
                log.warn("sceneCheckImage error: {}", jsonObject.getString("responseMsg"));
            }
        } catch (Exception e) {
            log.error("sceneCheckImage error :", e);
        }
        return false;
    }

    @Override
    public boolean sceneCheckResult(CheckResult checkResult) {
        try {
            // 判断缓存中的数据，是否所有场景都已回传结果  LoginUser user = redisCache.getCacheObject(key);
            // redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

            /*String redisKey = "task_result_" + checkResult.getTaskId();
            Map<String, String> map =  redisCache.getCacheMap(redisKey);

            if (map == null || map.get("checkResult.getSceneId()") == null) {
                map = new HashMap<>();
                map.put(checkResult.getSceneId(), checkResult.getSceneId());
            } else {
                String value = map.get("checkResult.getSceneId()");
            }
            redisCache.setCacheMap(redisKey, map);
            redisCache.expire(redisKey, 1, TimeUnit.DAYS);*/

            boolean flag = true;
            if(flag){
                TaskDetail taskDetail = new TaskDetail();
                taskDetail.setTaskId(checkResult.getTaskId());
                taskDetail.setTaskStatus("05");
                taskDetailMapper.updateTaskDetailStatusByTaskId(taskDetail);
            }

            List<RiskDetailInfo> riskDetailInfoList = new ArrayList<>();

            RiskDetailInfo riskDetailInfo = null;
            if (checkResult.getRiskData() != null) {
                for (CheckRisk checkRisk : checkResult.getRiskData()) {
                    riskDetailInfo = new RiskDetailInfo();
                    riskDetailInfo.setUid(UUID.uuid());
                    riskDetailInfo.setTaskId(checkResult.getTaskId());
                    riskDetailInfo.setSceneId(checkResult.getSceneId());
                    riskDetailInfo.setRiskReason(checkRisk.getRiskReason());
                    if(StringUtils.length(checkRisk.getRiskStartTime()) == 14){
                        // 将日期格式 yyyyMMddHHmmss转换yyyy-MM-dd HH:mm:ss
                        riskDetailInfo.setRiskStartTime(
                                DateUtils.convertToCompactFormat2(checkRisk.getRiskStartTime()));
                        riskDetailInfo.setRiskEndTime(
                                DateUtils.convertToCompactFormat2(checkRisk.getRiskEndTime()));
                    } else if(StringUtils.length(checkRisk.getRiskStartTime()) == 6) {
                        // 查询数据库的采集时间拼接
                        TaskDetail taskDetail = taskDetailMapper.queryTaskDetailByTaskId(checkResult.getTaskId());
                        String date = taskDetail.getStartTime().substring(0, 10).replace("-", "");
                        riskDetailInfo.setRiskStartTime(DateUtils.convertToCompactFormat2(
                                date + checkRisk.getRiskStartTime()));
                        riskDetailInfo.setRiskEndTime(DateUtils.convertToCompactFormat2(
                                date + checkRisk.getRiskEndTime()));
                    }
                    riskDetailInfoList.add(riskDetailInfo);

                    if (!CollectionUtils.isEmpty(checkRisk.getRiskImages())) {
                        int sort = 0;
                        for (String image :checkRisk.getRiskImages()) {
                            TaskRiskImage riskImage = new TaskRiskImage();
                            riskImage.setTaskId(riskDetailInfo.getTaskId());
                            riskImage.setUid(riskDetailInfo.getUid());
                            riskImage.setSortNo(sort++);
                            riskImage.setRiskImage(image);
                            taskExecutor.execute(() -> sceneCheckImage(riskImage));
                        }
                    }
                }
            }

            if (riskDetailInfoList.isEmpty()) {
                return true;
            }

            return sceneCheckResult(riskDetailInfoList);
        } catch (BaseException ex) {
            throw ex;
        } catch (Exception e) {
            log.error("sceneCheckResult error ", e);
        }
        return false;
    }

    @Override
    public List<String> queryRiskImage(String id) {
        try {

            log.info("queryRiskImage begin id = {}", id);
            // 查询数据库
            TaskDetailResult detailResult = taskDetailResultMapper.selectTaskDetailResultById(id);

            if (detailResult == null) {
                return new ArrayList<>();
            }

            log.info("queryRiskImage db id = {}", detailResult.getId());

            Map<String, String> map = new HashMap<>();
            map.put("task_id", detailResult.getTaskId());
            map.put("risk_id", detailResult.getId());

            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", MediaType.APPLICATION_JSON_VALUE);

            String url = agentServerIp + "/api/v1/file/get_risk_images";

            String params = JSON.toJSONString(map);

            String rspStr = HttpUtils.sendPost(url, params, headers, 10000);

            JSONObject jsonObject = JSON.parseObject(rspStr);
            if (StringUtils.equals(jsonObject.getString("responseCode"), "0")) {
                JSONArray data = jsonObject.getJSONObject("responseData").getJSONArray("data");
                return data.toJavaList(String.class);
            } else {
                log.warn("queryRiskImage error: {}", jsonObject.getString("responseMsg"));
            }
        } catch (Exception e) {
            log.error("queryRiskImage error :", e);
        }
        return new ArrayList<>();
    }
}
